%% Get Data
global forecastDays;
forecastDays= 5;

outputPoblacion = zeros(length(tabladatos(:,1)),length(poblacion(:,1)));
parfor hab=1:length(poblacion(:,1))
    outputPoblacion(:,hab)=outputSistemas(poblacion(hab,:),tabladatos);
end

N = length(outputPoblacion(:,1));


hab=1;%Bucle for
r=outputPoblacion(:,hab);
r=diff(r);
%% Pruebas
%dem2gbp = price2ret(Data);
close all
[coeff,errors,LLF,innovations,sigmas] = garchfit(r);
%tolerance 0.1

rng('default')
[e1,s1,y1] = garchsim(coeff,forecastDays,1);
garchplot(e1,s1,y1)
%tolerance 0.05

rng('default')
[e5,s5,y5] = garchsim(coeff,forecastDays,1,[],[],0.05);
garchplot(e5,s5,y5)


%% Model - best model
[bestp, bestq] = OptimizeGarch(r);

%% Garch 
bestp=0;
bestq=3;

model = garchset('p',bestp,'q',bestq);
fit=garchfit(model,r);
[SigmaForecast,MeanForecast,SigmaTotal,MeanRMSE]=garchpred(fit,r,forecastDays);



%% Forecast 5 days
model = garch(bestp , bestq);
fit= estimate(model,r);
Vf = forecast(fit,forecastDays,'Y0',r);
%% Plot forecast
V = infer(fit,r);

figure(1)
plot(V,'Color',[.7,.7,.7])
hold on
plot(N+1:N+forecastDays,Vf,'r','LineWidth',2)
xlim([1,N+forecastDays])
legend('Inferred','Forecast','Location','Northwest')
title(strcat('Conditional Variance Forecasts for -',celltickers(hab)))
hold off
%% Plot conditional variance forecasts for 1000 days.
Vf1000 = forecast(fit,1000,'Y0',r);

figure(2)
plot(Vf1000,'r','LineWidth',2)
title('Conditional Variance Forecast Asymptote')